package com.xuecheng.media.common.utils;

import com.xuecheng.media.config.AliyunLiveConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * 阿里云直播服务工具类
 */
@Slf4j
@Component
public class AliyunLiveUtil {

    /**
     * 根据课程发布id、课程计划id生成推流地址
     * @param coursePubId 课程发布id
     * @param teachplanId 课程计划id
     * @param liveConfig 阿里云直播配置
     * @return
     */
    public static String getLivePushUrl(Long coursePubId, Long teachplanId, AliyunLiveConfig liveConfig) {
        String uri = "/app" + coursePubId + "/stream" + teachplanId;

        LocalDateTime validTime = LocalDateTime.now().
            plusSeconds(liveConfig.getAliyunLivePushValidTime());
        Long validSecond = validTime.toEpochSecond(ZoneOffset.of("+8"));

        String keyString = uri + "-" + 
            validSecond + "-0-0-" + liveConfig.getAliyunLivePushKey();
        String md5Key = DigestUtils.md5Hex(keyString);

        String pushUrl = liveConfig.getAliyunLivePushDomain() + 
            uri + "?auth_key=" + validSecond + "-0-0-" + md5Key;

        return pushUrl;
    }

    /**
     * 根据课程发布id、课程计划id生成播流地址
     *   播放地址示例：
     *      xcpull.itheima.net/app24/stream49?auth_key=1616036657-0-0-
     			19e103673286fbf7a7fe0fa593511fae
     *
     *                  19e103673286fbf7a7fe0fa593511fae：
     *                       md5 ( uri + ‘-’ + 1616036657 + ‘-0-0-’ + securitykey )
     *
     * @param coursePubId 课程发布id
     * @param teachplanId 课程计划id
     * @param liveConfig 阿里云直播配置
     * @return
     */
    public static String getLivePullUrl(Long coursePubId, Long teachplanId, AliyunLiveConfig liveConfig) {
        String uri = "/app" + coursePubId + "/stream" + teachplanId;

        LocalDateTime validTime = LocalDateTime.now().
            plusSeconds(liveConfig.getAliyunLivePullValidTime());
        Long validSecond = validTime.toEpochSecond(ZoneOffset.of("+8"));

        String keyString = uri + "-" + validSecond + "-0-0-" 
            + liveConfig.getAliyunLivePullKey();
        String md5Key = DigestUtils.md5Hex(keyString);

        String pullUrl = liveConfig.getAliyunLivePullDomain() + 
            uri + "?auth_key=" + validSecond + "-0-0-" + md5Key;

        return pullUrl;
    }
}